/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.iec.edp.caf.commons.cryptography.generator;

import io.iec.edp.caf.commons.cryptography.service.SaltGenerator;

import java.nio.charset.StandardCharsets;

/**
 * This will always return the same salt. This salt is returned as bytes
 * using the UTF-8 .
 * <p>
 * If the requested salt has a size in bytes smaller than the specified salt,
 * the first n bytes are returned. If it is larger, an exception is thrown.
 *
 * @author Daniel Fern&aacute;ndez
 * @since 1.9.2
 */
public class StringFixedSaltGenerator implements SaltGenerator {

    private byte[] saltBytes;

    /**
     * Creates a new instance of <tt>FixedStringSaltGenerator</tt> using
     * the default charset.
     *
     * @param salt the specified salt.
     */
    public StringFixedSaltGenerator(String salt) {
        if (salt == null) {
            salt = "";
        }

        this.saltBytes = salt.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * Return salt with the specified byte length.
     *
     * @param lengthBytes length in bytes.
     * @return the generated salt.
     */
    public byte[] generateSalt(final int lengthBytes) {
        if (this.saltBytes.length < lengthBytes) {
            throw new RuntimeException("Requested salt larger than set");
        }

        final byte[] generatedSalt = new byte[lengthBytes];
        System.arraycopy(this.saltBytes, 0, generatedSalt, 0, lengthBytes);
        return generatedSalt;
    }
}
